package com.study.order.amqp;

import org.springframework.amqp.core.AmqpAdmin;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * 使用RabbitMq
 * 1.引入RabbitMq场景 RabbitAutoConfiguration 就会自动生效
 * 2.给容器自动配置了 RabbitTemplate AmqpAdmin RabbitMessagingTemplate CachingConnectionFactory
 * 2.1所有的属性都是在这配置的
 *
 * @ConfigurationProperties(prefix = "spring.rabbitmq")
 * public class RabbitProperties {
 */
@Configuration
public class RabbitMqCreate {

    @Autowired
    private AmqpAdmin amqpAdmin;

    /**
     * 创建一个交换机
     */
    @Bean
    public void createExchange() {
        /**
         * public DirectExchange(String name, boolean durable, boolean autoDelete, Map<String, Object> arguments)
         *                       交换机名称,是否持久化,是否自动删除,创建交换机指定的参数
         */
        DirectExchange directExchange = new DirectExchange("order-exchange", true, false);
        amqpAdmin.declareExchange(directExchange);
    }

    /**
     * 创建一个队列
     */
    @Bean
    public void createQueue() {
        /**
         * public Queue(String name, boolean durable, boolean exclusive, boolean autoDelete,@Nullable Map<String, Object> arguments)
         *               队列名称,是否持久化，是否为排他的,是否自动删除,创建队列指定的参数
         */
        Queue queue = new Queue("order-queue", true, false, false);
        amqpAdmin.declareQueue(queue);
    }

    /**
     * 绑定交换机和队列
     */
    @Bean
    public void createBinding() {
        /**
         * Binding(String destination, DestinationType destinationType, String exchange, String routingKey,@Nullable Map<String, Object> arguments)
         *          目的地,目的地类型,交换机,路由键,自定义参数
         * 将exchange指定的交换机和 destination目的地进行绑定,使用 routingKey 作为指定路由键
         */
        Binding binding = new Binding("order-queue", Binding.DestinationType.QUEUE,"order-exchange","order-key",null);
        amqpAdmin.declareBinding(binding);
    }

}
